<script setup lang="ts">

import {message} from "ant-design-vue";
import {getCurrentInstance} from "vue";
import BaseApp from "~/contentScripts/views/sycm/baseApp.vue";
import User from "~/contentScripts/views/tao/list/components/user.vue";
import {isLogin} from "~/logic";
import SYCM from "~/utils/ali/sycm";
import {searchAnalyzeInterception} from "~/utils/interception/sycm/searchAnalyzeInterception";
import Trans from "~/utils/sycm/trans";

const {proxy} = getCurrentInstance();
const $req = proxy.$req;
const state = reactive<any>({
  loginVisible: false,
  visible: false,
  tabs: [],
  data: [],
  activeCateId: '',
  showZs: false,
  loading: false,
});
const indexesMap: any = {
  clickHits: ['点击人气', '点击人数', true],
  clickHitsRatio: ['点击人气占比', '点击人数占比', false],
  clickHot: ['点击热度', '点击次数', true],
  clickRate: ['点击率', '点击率', false],
};
const __option = getCurrentInstance()?.appContext.provides.option;
const handle = async () => {
  if (isLogin({
    emit: () => {
      state.loginVisible = true;
    }
  }, __option)) {
    state.visible = true;
    state.tabs = await SYCM.getInternalFiberData('div.oui-card-content', 'memoizedProps.children[0].props.data')
    if (!state.tabs) {
      message.error('Tab数据获取失败，请重试~');
      return;
    }
    await loadData();
    // console.log(state.tabs, state.data);
    if (!state.data) {
      message.error('数据获取失败，请重试~');
      return;
    }
    if (!state.activeCateId) {
      state.activeCateId = state.tabs[0].cateId
    }
    state.visible = true;
  }
}
const columns = ref<any>([]);
const calcTable = () => {
  // 计算columns 根据indexesMap
  let cols = [];
  for (let key in indexesMap) {
    if (!indexesMap[key][2]) { // 百分比的
      cols.push({
        title: state.showZs ? indexesMap[key][0] : indexesMap[key][1],
        dataIndex: key,
        key: key,
        // width: 100,
        align: 'right',
        sorter: (a, b) => a[key] - b[key],
        dataType: 'customRender',
        render: (text, record, index) => {
          return (text * 100).toFixed(2) + '%'
        }
      })
    } else {
      cols.push({
        title: state.showZs ? indexesMap[key][0] : indexesMap[key][1],
        dataIndex: key,
        key: key,
        // width: 100,
        align: 'right',
        sorter: (a, b) => a[key] - b[key],
        dataType: 'customRender',
        render: (text, record, index) => {
          if (state.showZs) {
            return Trans.number(text).toFixed(2)
          } else {
            return text.toFixed(2);
          }
        }
      })
    }
  }
  columns.value = [
    { // 类目名称
      title: '类目ID',
      dataIndex: 'cateId',
      key: 'cateId',
      width: 100,
      align: 'left',
      sorter: (a, b) => a.cateId - b.cateId,
      fixed: 'left',
    },
    { // 类目名称
      title: '类目名称',
      dataIndex: 'cateName',
      key: 'cateName',
      width: 100,
      align: 'left',
      tooltip: true,
      sorter: (a, b) => a.cateName - b.cateName,
      fixed: 'left',
    },
    ...cols,
  ];
}
const loadData = async () => {
  state.loading = true;
  let data = $req.getResponse(searchAnalyzeInterception[2]);
  if (typeof data.__options.params.level1Id !== 'undefined' && data.__options.params.level1Id == state.activeCateId) {
    state.loading = false;
    state.data = data.data.data;
  } else {
    setTimeout(() => {
      loadData()
    }, 300);
  }
}
watch(() => state.activeCateId, async (activeCateId) => {
  if (activeCateId) {
    // 获取再tabs中的索引
    const index = state.tabs.findIndex(tab => tab.cateId === activeCateId);
    let oldData = [...state.data]
    state.data = [];
    document.querySelector("div.oui-card-content > span > div.oui-tab-switch-item-custom:nth-child(" + (index + 1) + ")").click();
    await loadData();
  }
})
watch(() => state.showZs, () => {
  calcTable();
});
watch(() => state.data, () => {
  calcTable();
}, {deep: true});
watch(() => state.tabs, () => {
  calcTable();
}, {deep: true});
</script>

<template>
  <base-app>
    <a-button-group>
      <user style="margin-right: 0"/>
      <a-button type="primary" size="small" @click="handle">一键转化</a-button>
    </a-button-group>
    <custom-modal v-model:visible="state.visible" width="95%" title="市场-搜索分析-类目构成">
      <template #headerRight>
        <s-y-c-m-custom-modal-header-notice/>
        <div style="display: inline-block;padding-left: 10px;">
          显示指数
          <a-checkbox v-model:checked="state.showZs"/>
        </div>
      </template>
      <div style="max-height: calc(100vh - 150px);overflow-y: auto;padding-top: 10px;">
        <a-row :gutter="20" class="tabs" style="margin-right: 0;margin-left: 0;">
          <a-col v-for="(tab,index) in state.tabs" :key="tab.cateId" :span="4">
            <div class="tab" :class="{
              active: state.activeCateId === tab.cateId
            }"
                 @click="state.activeCateId = tab.cateId"
            >
              <h3>{{ tab.cateName }}</h3>
              <div class="item">
                <div class="label">
                  {{ state.showZs ? indexesMap.clickHits[0] : indexesMap.clickHits[1] }}
                </div>
                <div class="content">
                  {{ !state.showZs ? Trans.number(tab.clickHits) : tab.clickHits.toFixed(2) }}
                </div>
              </div>
              <div class="item">
                <div class="label">
                  {{ state.showZs ? indexesMap.clickHitsRatio[0] : indexesMap.clickHitsRatio[1] }}
                </div>
                <div class="content">
                  {{ (tab.clickHitsRatio * 100).toFixed(2) }}%
                </div>
              </div>
              <div class="item">
                <div class="label">
                  {{ state.showZs ? indexesMap.clickHot[0] : indexesMap.clickHot[1] }}
                </div>
                <div class="content">
                  {{ !state.showZs ? Trans.number(tab.clickHot) : tab.clickHot.toFixed(2) }}
                </div>
              </div>
              <div class="item">
                <div class="label">
                  {{ state.showZs ? indexesMap.clickRate[0] : indexesMap.clickRate[1] }}
                </div>
                <div class="content">
                  {{ (tab.clickRate * 100).toFixed(2) }}%
                </div>
              </div>
            </div>
          </a-col>
        </a-row>
        <a-spin :spinning="state.loading">
          <base-table :data-source="state.data" table-name="市场-搜索分析-类目构成" size="small" :columns="columns"
                      :scroll="{
            y:500,
          }"
          >

          </base-table>
        </a-spin>
      </div>
    </custom-modal>
    <user-login-modal v-model:login-visible="state.loginVisible"/>
  </base-app>
</template>

<style lang="less" scoped>
.tabs {
  margin-left: 0;
  margin-right: 0;
  // flex两侧留空
  justify-content: center;

  .tab {
    border: 1px solid #eee;
    border-radius: 5px;
    padding: 10px;
    cursor: pointer;
    margin-bottom: 10px;

    h3 {
      margin-bottom: 10px;
      font-size: 14px;
    }

    &.active {
      background-color: #fff;
      border: 2px solid #0079fe;
    }

    &:hover {
      background-color: #fff;
      border: 2px solid #0079fe;
      // 阴影
      box-shadow: 0 0 10px #000;
    }

    .item {
      display: flex;
      line-height: 1.5;
      font-size: 12px;

      .label {
        text-align: right;
        margin-right: 10px;
        color: #666;
      }

      .content {
        flex: 1;
        text-align: right;
        color: #666;
      }

    }
  }
}
</style>
